<!-- eslint-disable vue/multi-word-component-names -->
<!-- eslint-disable no-unused-vars -->
<script setup>
import { onMounted, onUnmounted, reactive, ref, getCurrentInstance } from 'vue'
import { useI18n } from 'vue-i18n'
import { ImgWasm, convertImage } from '@/utils/wasm/index'
import { create_note } from '@/utils/api/note'
import { stringToBase64 } from '@/utils/note'
import { uploadFile } from '@/utils/api/image/upload'

import Text from '@tiptap/extension-text'
import ListItem from '@tiptap/extension-list-item'
import StarterKit from '@tiptap/starter-kit'
import Placeholder from '@tiptap/extension-placeholder'
import { Editor, EditorContent } from '@tiptap/vue-3'

import Bowser from 'bowser'
const app = getCurrentInstance()
const { dayjs } = app.appContext.app.config.globalProperties

import { filterNoteTags } from '@/utils/note'
import { AlexMsg } from '@2473o/alexui'

import { emitter } from '@/utils'
import { setBind } from '@/utils/api/image'

const { t } = useI18n()

const _data = reactive({
  loading: true,
  isPublic: true
})

const loadWasm = async () => {
  await ImgWasm()
  console.log('WASM module ImgConvert loaded')
}

const extensions = ref([
  StarterKit.configure({
    heading: false, // 禁用默认的 heading 扩展
    inputRules: false // 禁用默认的 inputRules 扩展
  }),
  Text,
  Placeholder.configure({
    placeholder: t('common.What are you thinking, write it down?')
  }),
  ListItem
])

const editor = new Editor({
  content: '',
  extensions: extensions.value,
  autofocus: true
})

const detect_content = () => {
  let text = editor.getText()
  if (text) {
    return true
  }
  return false
}

const createNote = async () => {
  let browser = Bowser.parse(window.navigator.userAgent)
  let content = editor.getHTML()

  if (!detect_content()) {
    AlexMsg({ type: 'warning', text: `请输入内容哦` })
    return
  }

  // 理想
  // let data = {
  //   type: 'note',
  //   status: _data.isPublic,
  //   content,
  //   createTime: new Date().getTime(),
  //   updateTime: new Date().getTime(),
  //   tags: filterNoteTags(content),
  //   category: [],
  //   mark: {
  //     ...browser
  //   },
  //   images: []
  // }

  // 现实
  let data = {
    createTime: dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss'),
    updateTime: dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss'),
    noteClassify: JSON.stringify(filterNoteTags(content) || []),
    noteContext: stringToBase64(content),
    noteFrom: JSON.stringify(browser)
  }

  _data.loading = true
  let res = await create_note(data)

  if (res.code == 200) {
    let note_id = res.id
    if (images.meta.length > 0) {
      for (let index = 0; index < images.bin.length; index++) {
        const element = images.bin[index]
        let data = await uploadFile(element, images.meta[index].name)
        await setBind(1, note_id, data.fileName)
        //         {
        //     "msg": "操作成功",
        //     "fileName": "/profile/upload/2024/08/16/屏幕截图 2024-05-28 013325_20240816013301A001.",
        //     "code": 200,
        //     "newFileName": "屏幕截图 2024-05-28 013325_20240816013301A001.",
        //     "url": "http://docs.feli.top:2473/profile/upload/2024/08/16/屏幕截图 2024-05-28 013325_20240816013301A001.",
        //     "originalFilename": "屏幕截图 2024-05-28 013325"
        // }
        removeImage(index)
      }
    }
    _data.loading = false
    editor.commands.setContent('')
    AlexMsg({ type: 'success', text: t('common.Successfully') })
  } else {
    AlexMsg({ type: 'error', text: t('common.Failed') + `: ${res.message}` })
  }
}

const addTag = () => {
  editor.commands.insertContent('#')
}

const imageInput = ref(null)
const images = reactive({
  meta: [],
  bin: []
})
const addImage = () => {
  imageInput.value.click()
}
const handleFileUpload = async (event) => {
  const files = event.target.files
  for (const file of files) {
    const convertedBlob = await convertImage(file, 'webp')
    const nameWithoutExtension = file.name.split('.').slice(0, -1).join('.')
    const url = URL.createObjectURL(convertedBlob)

    images.meta.push({ name: nameWithoutExtension, url })
    images.bin.push(convertedBlob)
  }
}

const removeImage = (index) => {
  images.meta.splice(index, 1)
  images.bin.splice(index, 1)
}

const emojis = ref([
  '🥳',
  '😀',
  '😂',
  '😉',
  '😘',
  '😍',
  '🤪',
  '😓',
  '🙁',
  '😕',
  '😳',
  '😱',
  '😧',
  '😡',
  '👨🏻‍💻',
  '🙅🏻‍♂️',
  '🎉',
  '👏',
  '🎁',
  '🚀',
  '🌈'
])
const addEmoji = (emoji) => {
  editor.commands.insertContent(emoji)
}

const actions = ref([
  {
    name: 'ul',
    icon: '/dashicons/editor-ul.svg',
    fn: () => {
      editor.chain().focus().toggleBulletList().run()
    },
    active: false
  },
  {
    name: 'ol',
    icon: '/dashicons/editor-ol.svg',
    fn: () => {
      editor.chain().focus().toggleOrderedList().run()
    },
    active: false
  },
  {
    name: 'bold',
    icon: '/dashicons/editor-bold.svg',
    fn: () => {
      editor.commands.toggleBold()
    },
    active: false
  },
  {
    name: 'italic',
    icon: '/dashicons/editor-italic.svg',
    fn: () => {
      editor.commands.toggleItalic()
    },
    active: false
  }
])

const handleQuote = (noteId) => {
  editor.commands.insertContent(` /note/${noteId}`)
}

onMounted(async () => {
  await loadWasm()
  _data.loading = false
  emitter.on('use-Quote', handleQuote)
})
onUnmounted(() => {
  emitter.off('use-Quote')
})
</script>

<template>
  <!-- 笔记编辑开始 -->

  <div class="editor-box d-flex mb-2">
    <div class="editor">
      <div v-if="_data.loading" class="loading loading-full"></div>
      <editor-content :editor="editor" />

      <!-- 笔记编辑结束 -->

      <!-- 笔记附件开始 -->
      <div class="attachment" style="margin: 1% 0px 0px">
        <template v-for="(item, index) in images.meta" :key="index">
          <span
            :data-tooltip="item.name"
            class="chip bg-gray text-gray m-1 tooltip"
            style="overflow: unset"
          >
            <div class="divider-vert px-1"></div>
            <a class="file" :href="item.url" target="_blank" style="color: currentcolor">{{
              item.name
            }}</a>
            <a
              href="javascript:void(0);"
              @click="removeImage(index)"
              aria-label="Close"
              role="button"
              class="btn btn-clear"
            ></a>
          </span>
        </template>
      </div>
      <!-- 笔记附件结束 -->

      <!-- 笔记功能开始 -->
      <div class="editor-footer flex-center justify-between">
        <div class="editor-tool d-flex">
          <!-- 添加标签 "#XXX" -->
          <button class="btn btn-link btn-action btn-sm flex-center" @click="addTag">#</button>

          <!-- 添加表情 -->
          <div class="popover popover-bottom">
            <button class="btn btn-link btn-action btn-sm flex-center">
              <AlexSVG src="/dashicons/smily.svg" color="#818ea3" width="0.8rem" />
            </button>
            <div class="editor-tool-emoji popover-container">
              <div class="card uni-card card uni-card uni-bg uni-shadow bg-blur">
                <div class="card-body flex-center" style="flex-wrap: wrap">
                  <button
                    class="btn btn-link btn-action flex-center"
                    v-for="(item, index) in emojis"
                    @click="addEmoji(item)"
                    :key="index"
                    v-html="item"
                  ></button>
                </div>
              </div>
            </div>
          </div>

          <!-- 富文本 actions 切换 -->
          <template v-for="(item, index) in actions" :key="index">
            <button
              class="btn btn-link btn-action btn-sm flex-center"
              :class="{ active: item.active }"
              @click="(item.active = !item.active), item.fn()"
            >
              <AlexSVG :src="item.icon" color="#818ea3" width="0.75rem" />
            </button>
          </template>

          <!-- 添加图片 -->
          <!-- <button  @click="login({username: 'admin', password: 'admin123'})">登录</button>
      <button @click="uploadFile">上传</button> -->
          <input
            type="file"
            ref="imageInput"
            accept="image/png, image/jpeg, image/png"
            multiple
            @change="handleFileUpload"
            class="d-none"
          />
          <button class="btn btn-link btn-action btn-sm flex-center" @click="addImage">
            <AlexSVG src="/dashicons/cloud-upload.svg" color="#818ea3" width="0.75rem" />
          </button>
        </div>

        <!-- 笔记功结束 -->

        <div class="flex-center">
          <a
            href="javascript:void(0);"
            class="btn-private btn btn-link btn-sm flex-center mr-2"
            :class="{ active: !_data.isPublic }"
            @click="_data.isPublic = !_data.isPublic"
          >
            {{ _data.isPublic ? '公开' : '私密' }}
          </a>
          <button class="editor-send btn btn-primary btn-sm flex-center" @click="createNote">
            <!-- <i class="dashicons dashicons-edit-page mr-1"></i> -->
            <AlexSVG src="/dashicons/cloud-upload.svg" color="#fff" height="1rem" />
            发送
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.btn {
  &.btn-link {
    &:hover,
    &:focus {
      .alex-icon {
        --color: #3366ff !important;
      }
    }
    &:focus {
      box-shadow: none;
    }
    &:hover {
      box-shadow: 0 0 0 0.1rem rgba(51, 102, 255, 0.2);
    }

    &.active {
      background-color: rgba(51, 102, 255, 0.1);
      .alex-icon {
        --color: #3366ff !important;
      }
    }
  }
}

.attachment {
  a.file {
    max-width: 5em;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

.editor {
  :deep(.tiptap) {
    font-size: 0.7rem;
    padding: 0.4rem !important;
    outline: none;

    ol,
    ul {
      margin: 0;
      li:first-child {
        margin: 0;
      }
      li p {
        display: inline-block;
      }
    }
    p {
      margin: 0;

      &.is-editor-empty:first-child::before {
        color: #adb5bd;
        content: attr(data-placeholder);
        float: left;
        height: 0;
        pointer-events: none;
      }
    }

    ol {
      list-style: decimal inside !important;
    }
  }
}
</style>
